layui.use(['element', 'form', 'upload', 'xmSelect', 'jquery'], function () {
    var element = layui.element;
    var form = layui.form;
    var $ = layui.jquery;
    var upload = layui.upload;
    var xmSelect = layui.xmSelect;


    $("#addBtn>button").click(function () {
        var type = $(this).data("type");
        var formId = $("input[name=formId]").val();
        $("form#example-form").attr("id", formId);
        $("form#" + formId).attr("lay-filter", $("input[name=formFilter]").val());
        if (type === "submit") {
            renderHtmlPart({type: "submit"}, $, form, formId);
            renderJsPart({type: "submit"});
        } else {
            admin.open({
                type: 1,
                title: '表单元素信息',
                fixed: true,
                offset: '50px',
                area: '550px',
                content: $('#addFormDialog').html(),
                success: function (layero, dIndex) {
                    $(layero).children('.layui-layer-content').css('overflow', 'visible');
                    form.val('addForm', {type: type});
                    if (type === "switch" || type === "radio"
                        || type === "select" || type === "checkbox"
                        || type === "xmSelect") {
                        $("#" + type + "Txt").removeClass("layui-hide");
                    }
                    form.render();
                    // 表单提交事件
                    form.on('submit(dialogEditSubmit1)', function (data) {
                        renderHtmlPart(data.field, $, form, formId);
                        renderJsPart(data.field);
                        layer.close(dIndex);
                        return false;
                    });

                }
            });
        }
    });

    form.on('select(tableName)', function (data) {
        // console.log(data);
        admin.req(prefix + "/genMapper", {
            tableId: data.value
        }, function (resp) {
            himio.notice.resp(resp, function () {
                $("textarea[name=mapper]").val(resp.data.mapper);
                $("textarea[name=service]").val(resp.data.service);
            }, true);
        }, 'post');
    });

});


var resultTpl;

function renderHtmlPart(dataField, $, form, formId) {
    var type = dataField.type;
    var strVar = "\n";
    if (type === "text" || type === "password") {
        resultTpl = tpl.textOrPassword(dataField, strVar);
    } else if (type === "switch") {
        resultTpl = tpl.switchElem(dataField, strVar);
    } else if (type === "radio") {
        resultTpl = tpl.radio(dataField, strVar);
    } else if (type === "select") {
        resultTpl = tpl.select(dataField, strVar);
    } else if (type === "checkbox") {
        resultTpl = tpl.checkbox(dataField, strVar);
    } else if (type === "textarea") {
        resultTpl = tpl.textarea(dataField, strVar);
    } else if (type === "upload") {
        resultTpl = tpl.upload(dataField, strVar);
    } else if (type === "xmSelect") {
        resultTpl = tpl.xmSelect(dataField, strVar);
    } else if (type === "xmSelect") {
        resultTpl = tpl.xmSelect(dataField, strVar);
    } else if (type === "tinymce") {
        resultTpl = tpl.tinymce(dataField, strVar);
    } else if (type === "submit") {
        resultTpl = tpl.submit(dataField, strVar);
    }
    if (formId) {
        $("#" + formId).append(resultTpl);
    } else {
        $("#example-form").append(resultTpl);
    }
    syncCode();
    form.render();
    if (type === "upload") {
        initUploadInForm(upload,
            dataField.fieldName,
            '#' + dataField.fieldName + 'List',
            $('#' + dataField.fieldName + 'FileList'),
            "/common/upload",
            "#" + dataField.fieldName + "ListAction",
            $('#' + dataField.fieldName + 'ListAction'),
            dataField.fieldName);
    } else if (type === "xmSelect") {
        var xmSelectTxts = dataField.xmSelectTxt;
        if (xmSelectTxts) {
            var xsts = xmSelectTxts.split("\n");
            var dataArr = [];
            for (var i = 0; i < xsts.length; i++) {
                if (xsts[i]) {
                    dataArr.push({
                        name: xsts[i].split(",")[0],
                        value: xsts[i].split(",")[1]
                    })
                }
            }
            xmSelect.render({
                el: '#' + dataField.fieldName + 'Sel',
                tips: '请选择' + dataField.fieldCnName,
                name: dataField.fieldName,
                layVerify: dataField.required && dataField.required === '1' ? 'required' : '',
                layVerType: 'tips',
                filterable: true,
                height: 350,
                data: dataArr
            });
        }
    } else if (type === "tinymce") {
        renderTinyMce('#' + dataField.fieldName + 'Editor', 480, "/common/upload");
    }

}

function renderJsPart(dataField) {
    var type = dataField.type;
    var tpl = "&lt;script&gt;\n";
    var useModule = "'element','form'";
    var useInit = "";
    if (type === "upload") {
        useModule += ",'upload'"
        useInit += "    initUploadInForm(upload, " + dataField.fieldName + ", '#" + dataField.fieldName + "List', $('#" + dataField.fieldName + "FileList'), \"/common/upload\", \"#" + dataField.fieldName + "ListAction\", $('#" + dataField.fieldName + "ListAction'), '" + dataField.fieldName + "');\n";
    } else if (type === "xmSelect") {
        useModule += ",'xmSelect'";
        var xmSelectTxts = dataField.xmSelectTxt;
        if (xmSelectTxts) {
            var xsts = xmSelectTxts.split("\n");
            var dataArr = [];
            for (var j = 0; j < xsts.length; j++) {
                if (xsts[j]) {
                    dataArr.push({
                        name: xsts[j].split(",")[0],
                        value: xsts[j].split(",")[1]
                    })
                }
            }
            useInit += "    xmSelect.render({\n" +
                "                el: '#" + dataField.fieldName + "Sel',\n" +
                "                tips: '请选择" + dataField.fieldCnName + "',\n" +
                "                name:'" + dataField.fieldName + "',\n" +
                "                layVerify: '" + (dataField.required && dataField.required === '1' ? 'required' : '') + "',\n" +
                "                layVerType: 'tips',\n" +
                "                filterable: true,\n" +
                "                height: 350,\n" +
                "                data: " + JSON.stringify(dataArr) + "\n" +
                "            });\n";
        }
    } else if (type === "tinymce") {
        tpl += "<th:block th:include=\"include :: tinymceJs\"/>\n";
        useInit += "    renderTinyMce('#'" + dataField.fieldName + "'Editor', 480, \"/common/upload\");\n";
    } else if (type === "submit") {
        useInit += "    form.on('submit(formDemo)', function(){";
        useInit += "        admin.req('', {}, function(){}, 'post');";
        useInit += "    })";
    }

    tpl += "layui.use([" + useModule + "], function () {";
    var modules = useModule.split(",");
    tpl += "\n";
    for (var i = 0; i < modules.length; i++) {
        var module = modules[i].substring(1, modules[i].length - 1);
        tpl += "    var " + module + " = layui." + module + ";\n";
    }
    tpl += "\n    form.render();\n";
    tpl += useInit;
    tpl += "});\n";
    tpl += "&lt;/script&gt;";
    layui.$("#resource").html(layui.$("#resource").html() + "\n" + tpl);
}

//各种模板
var tpl = {
    //文本或者密码
    textOrPassword: function (dataField, strTpl) {
        var type = dataField.type;
        var display = dataField.display;
        var required = dataField.required;
        var style = dataField.style;
        strTpl += "    <div class=\"layui-form-item\">\n";
        strTpl += "        <label class=\"layui-form-label";
        if (dataField.required && dataField.required !== "0") {
            strTpl += " layui-form-required";
        }
        strTpl += "\">" + dataField.fieldCnName + "<\/label>\n";
        strTpl += "        <div class=\"" + display + "\">\n";
        strTpl += "            <label>\n";
        strTpl += "	              <input type=\"" + type + "\" name=\"" + dataField.fieldName + "\" placeholder=\"请输入" + dataField.fieldName + "\" ";
        if (style && style !== "") {
            strTpl += "style=\"" + dataField.style + "\"";
        }
        strTpl += " class=\"layui-input\" ";
        if (required === "1") {
            strTpl += "lay-verify=\"required\" lay-verType=\"tips\" required=\"required\"";
        }
        strTpl += "/>\n";
        strTpl += "            <\/label>\n";
        strTpl += "        <\/div>\n";
        strTpl += "    <\/div>\n";
        return strTpl;
    }
    //开关组件
    , switchElem: function (dataField, strTpl) {
        strTpl += "  <div class=\"layui-form-item\">\n";
        strTpl += "    <label class=\"layui-form-label";
        if (dataField.required && dataField.required !== "0") {
            strTpl += " layui-form-required";
        }
        strTpl += "\">" + dataField.fieldCnName + "<\/label>\n";
        strTpl += "    <div class=\"" + dataField.display + "\">\n";
        strTpl += "      <input type=\"checkbox\" name=\"" + dataField.fieldName + "\" lay-skin=\"switch\" ";
        if (dataField.switchTxt && dataField.switchTxt !== "") {
            strTpl += "lay-text=\"" + dataField.switchTxt + "\">\n";
        }
        strTpl += "    <\/div>\n";
        strTpl += "  <\/div>\n";
        return strTpl;
    }
    //单选框
    , radio: function (dataField, strTpl) {
        strTpl += "  <div class=\"layui-form-item\">\n";
        strTpl += "    <label class=\"layui-form-label";
        if (dataField.required && dataField.required !== "0") {
            strTpl += " layui-form-required";
        }
        strTpl += "\">" + dataField.fieldCnName + "<\/label>\n";
        strTpl += "    <div class=\"" + dataField.display + "\">\n";
        var radioTxt = dataField.radioTxt;
        var radioTxts = radioTxt.split("\n");
        for (var i = 0; i < radioTxts.length; i++) {
            var labelValue = radioTxts[i].split(",");
            var checked = i === 0 ? "checked" : "";
            strTpl += "      <input type=\"radio\" name=\"" + dataField.fieldName + "\" value=\"" + labelValue[1] + "\" title=\"" + labelValue[0] + "\"" + checked + ">\n";
        }
        strTpl += "    <\/div>\n";
        strTpl += "  <\/div>\n";
        return strTpl;
    }
    //下拉单选
    , select: function (dataField, strTpl) {
        strTpl += "  <div class=\"layui-form-item\">\n";
        strTpl += "    <label class=\"layui-form-label";
        if (dataField.required && dataField.required !== "0") {
            strTpl += " layui-form-required";
        }
        strTpl += "\">" + dataField.fieldCnName + "<\/label>\n";
        strTpl += "    <div class=\"" + dataField.display + "\" ";
        if (dataField.style && dataField.style !== "") {
            strTpl += "style=\"" + dataField.style + "\"";
        }
        strTpl += ">\n";
        strTpl += "      <select name=\"" + dataField.fieldName + "\" ";
        if (dataField.required && dataField.required !== "") {
            strTpl += "lay-verify=\"required\" lay-verType=\"tips\"";
        }
        strTpl += "lay-search>\n";
        var selectTxt = dataField.selectTxt;
        var selectTxts = selectTxt.split("\n");
        for (var i = 0; i < selectTxts.length; i++) {
            var labelValue = selectTxts[i].split(",");
            var selected = i === 0 ? "selected" : "";
            strTpl += "        <option value=\"" + labelValue[1] + "\" " + selected + ">" + labelValue[0] + "<\/option>\n";
        }
        strTpl += "      <\/select>\n";
        strTpl += "    <\/div>\n";
        strTpl += "  <\/div>\n";
        return strTpl;
    }
    //复选框
    , checkbox: function (dataField, strTpl) {
        strTpl += "  <div class=\"layui-form-item\">\n";
        strTpl += "    <label class=\"layui-form-label";
        if (dataField.required && dataField.required !== "0") {
            strTpl += " layui-form-required";
        }
        strTpl += "\">" + dataField.fieldCnName + "<\/label>\n";
        strTpl += "    <div class=\"" + dataField.display + "\">\n";
        var checkboxTxt = dataField.checkboxTxt;
        var checkboxTxts = checkboxTxt.split("\n");
        for (var i = 0; i < checkboxTxts.length; i++) {
            var labelValue = checkboxTxts[i].split(",");
            var checked = i === 0 ? "checked" : "";
            strTpl += "      <input type=\"checkbox\" name=\"" + dataField.fieldName + "[]\" value=\"" + labelValue[1] + "\" title=\"" + labelValue[0] + "\"" + checked + " lay-skin=\"primary\">\n";
        }
        strTpl += "    <\/div>\n";
        strTpl += "  <\/div>\n";
        return strTpl;
    }
    //文本域
    , textarea: function (dataField, strTpl) {
        strTpl += "  <div class=\"layui-form-item\">\n";
        strTpl += "    <label class=\"layui-form-label";
        if (dataField.required && dataField.required !== "0") {
            strTpl += " layui-form-required";
        }
        strTpl += "\">" + dataField.fieldCnName + "<\/label>\n";
        strTpl += "    <div class=\"" + dataField.display + "\">\n";
        strTpl += "      <textarea name=\"" + dataField.fieldName + "\" placeholder=\"请输入" + dataField.fieldCnName + "\" class=\"layui-textarea\"";
        if (dataField.required && dataField.required !== "0") {
            strTpl += " lay-verify=\"required\" lay-verType=\"tips\" required";
        }
        if (dataField.display && dataField.display !== "") {
            strTpl += " style=\"" + dataField.display + "\"";
        }
        strTpl += "><\/textarea>\n";
        strTpl += "    <\/div>\n";
        strTpl += "  <\/div>\n";
        return strTpl;
    }
    //上传域（单文件）
    , upload: function (dataField, strTpl) {
        strTpl += "<div class=\"layui-form-item\">\n";
        strTpl += "<input name=\"" + dataField.fieldName + "\" type=\"hidden\"/>\n";
        strTpl += "    <label class=\"layui-form-label";
        if (dataField.required && dataField.required !== "0") {
            strTpl += " layui-form-required";
        }
        strTpl += "\">" + dataField.fieldCnName + "<\/label>\n";
        strTpl += "    <div class=\"" + dataField.display + "\">\n";
        strTpl += "        <div class=\"layui-upload\">\n";
        strTpl += "            <button type=\"button\" class=\"layui-btn layui-btn-normal\" id=\"" + dataField.fieldName + "List\">选择文件<\/button>\n";
        strTpl += "            <button type=\"button\" class=\"layui-btn layui-btn-disabled\" id=\"" + dataField.fieldName + "ListAction\" disabled=\"disabled\">开始上传<\/button>\n";
        strTpl += "            <div class=\"layui-upload-list\" style=\"max-width: 1000px;\">\n";
        strTpl += "                <table class=\"layui-table\">\n";
        strTpl += "                    <colgroup>\n";
        strTpl += "                        <col>\n";
        strTpl += "                        <col>\n";
        strTpl += "                        <col>\n";
        strTpl += "                        <col>\n";
        strTpl += "                    <\/colgroup>\n";
        strTpl += "                    <thead>\n";
        strTpl += "                    <tr>\n";
        strTpl += "                        <th>文件名<\/th>\n";
        strTpl += "                        <th>大小<\/th>\n";
        strTpl += "                        <th>上传进度<\/th>\n";
        strTpl += "                        <th>操作<\/th>\n";
        strTpl += "                    <\/tr>\n";
        strTpl += "                    <\/thead>\n";
        strTpl += "                    <tbody id=\"" + dataField.fieldName + "FileList\"><\/tbody>\n";
        strTpl += "                <\/table>\n";
        strTpl += "            <\/div>\n";
        strTpl += "        <\/div>\n";
        strTpl += "    <\/div>\n";
        strTpl += "<\/div>\n";
        return strTpl;
    }
    //下拉多选
    , xmSelect: function (dataField, strTpl) {
        strTpl += "<div class=\"layui-form-item\">\n";
        strTpl += "    <label class=\"layui-form-label";
        if (dataField.required && dataField.required !== "0") {
            strTpl += " layui-form-required";
        }
        strTpl += "\">" + dataField.fieldCnName + "<\/label>\n";
        strTpl += "    <div class=\"" + dataField.display + "\">\n";
        strTpl += "        <div id=\"" + dataField.fieldName + "Sel\" class=\"xm-select-demo\"><\/div>\n";
        strTpl += "    <\/div>\n";
        strTpl += "<\/div>\n";
        return strTpl;
    }
    //富文本
    , tinymce: function (dataField, strTpl) {
        strTpl += "<div class=\"layui-form-item\">\n";
        strTpl += "    <label class=\"layui-form-label";
        if (dataField.required && dataField.required !== "0") {
            strTpl += " layui-form-required";
        }
        strTpl += "\">" + dataField.fieldCnName + "<\/label>\n";
        strTpl += "    <div class=\"" + dataField.display + "\">\n";
        strTpl += "        <label>\n";
        strTpl += "            <textarea id=\"" + dataField.fieldName + "Editor\" name=\"" + dataField.fieldName + "\"><\/textarea>\n";
        strTpl += "        <\/label>\n";
        strTpl += "    <\/div>\n";
        strTpl += "<\/div>\n";
        return strTpl;
    }
    //提交
    , submit: function (dataField, strTpl) {
        strTpl += "  <div class=\"layui-form-item\">\n";
        strTpl += "    <div class=\"layui-input-block\">\n";
        strTpl += "      <button class=\"layui-btn\" lay-submit lay-filter=\"formDemo\">立即提交<\/button>\n";
        strTpl += "      <button type=\"reset\" class=\"layui-btn layui-btn-primary\">重置<\/button>\n";
        strTpl += "    <\/div>\n";
        strTpl += "  <\/div>\n";
        return strTpl;
    }
}

//同步代码到textarea
function syncCode() {
    var html = layui.$("#example").html();
    var resCode = html.substr(41);
    layui.$("#resource").text(resCode);
}